package cn.itsource.service.impl;

import cn.itsource.pojo.domain.Department;
import cn.itsource.mapper.DepartmentMapper;
import cn.itsource.service.IDepartmentService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tt
 * @since 2024-09-09
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> getDeptList() {

        return getTree();
    }

    public List<Department> getTree() {
        //创建一个空集合装无限极数
        List<Department> departmentTree = new ArrayList<>();
        //查询所有的类型
        List<Department> departments = departmentMapper.findAll();

        //将所有的对象装到map中充当缓存【获取的时候通过key=id，获取对象】 //方便通过id获取类型对象
        Map<Long,Department> map = new HashMap<>();//缓存
        for (Department department : departments) {
            map.put(department.getId(),department);
        }

        //遍历所有的文章类型
        for (Department department : departments) {
            //如果ParentId为null = 顶级类型 = 直接装到无限极树
            if(department.getParentId() == null){//顶级菜单
                departmentTree.add(department);
            }else{//有上级类型 - 将自己装到父类型的children中【】
                //获取当前类型的父类型
                Long parentMenuId = department.getParentId();
                //根据父类型的id查询父类型的对象
                Department parentDepartment= map.get(parentMenuId);
                if(parentDepartment != null){
                    //获取父类型的集合
                    List<Department> children = parentDepartment.getChildren();
                    //将自己装到父类型的集合中
                    children.add(department);
                }
            }
        }
        return departmentTree;
    }

}
